package vendingmachine

import grails.converters.JSON
import com.tb.fb.Facebook
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import net.iasolution.vendingmachine.constance.*
class PosterService {
	def mailService
	def postResult(def cid){
		if(ShiroUser.findByCardId(cid)!=null){
			try{
				def message = getMessage(cid)
				if(message==null)
					return
				postFacebookMessage(cid,message) //FIXME
				postToUserMail(cid,message)
				PaymentMatch.findAllByCardId(cid).each{
					it.state = MatchState.findByName(VendingConstance.MATCH_STATE_USED)
					it.save(flush:true)

				}
			}catch(Exception e){
				e.printStackTrace()
			}
		}
	}

	private String getMessage(def cardId){
		if(PaymentMatch.countByCardId(cardId)==0)
			return null
		def message = "[${new Date(System.currentTimeMillis())}] congraduate you get new coupon : "
		def c = 0
		PaymentMatch.findAllByCardId(cardId).each {
			if(it.state.name==VendingConstance.MATCH_STATE_UN_USE){
				message += " ${it.coupon.item} : ${ConfigurationHolder.config.grails.serverURL}/information/showCoupon/${it.coupon.id} \n"
				c++
			}
		}
		//		println "total send message (${c}) from ${cardId}"
		return message
	}


	private void postToUserMail(def cid ,def message){
		def u = ShiroUser.findByCardId(cid)
		if(u!=null){
			println " ================ send mail to ${u.email} : ${message}"
			mailService.sendMail {
				to u.email
				//				from "iaSolution@iaSolution.net"
				subject "Hello ${u.username} !! You Get the New Coupons !!"
				body message
			}
		}
	}

	private void postFacebookMessage(def cid,def message) throws Exception{
		def u = ShiroUser.findByCardId(cid)
		if(u!=null){
			def facebook = new Facebook(u.authToken)
			def api = "https://graph.facebook.com/me/feed?"
			def access_token = u.authToken
			String postInfor = api + "&message=" + java.net.URLEncoder.encode(message, "UTF8") + "&method=POST" + "&access_token=" + access_token
			try{
				def json = JSON.parse(facebook.process(postInfor))
				println "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ resultJ = ${json}"
				println "---------------------------------------------------------"
				if(json.error!=null)
					throw new Exception("####################################### [send oauth error] ${json}")
			}catch(IOException e){
				throw new Exception("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& [send oauth error] ${e}")
			}
		}
	}



}
